<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Controllers\common\MyAgentController;
use App\Http\Controllers\Controller;
use DB;
class RoomController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    //位置列表页面方法
    public function getIndex(Request $request)
    {
        $get = array();
        $get['room'] = $request->input('room','');
        $get['area'] = $request->input('area','');
        $get['building'] = $request->input('building','');
        //获取登录id
        // $agentId = session('agentId');
        $agentId = $request->cookie('agentId');
        $get['ag'] = $request->input('ag',$agentId);
        //查询父级代理商path
        $path = DB::table('sa_agent') -> select('path') -> where(['id'=>$agentId]) -> first();
        $len = substr_count($path['path'],',');
        $agent = MyAgentController::allAgent($agentId);
        foreach ($agent as $k=>$v){
            $agent[$k]['agent_name'] = str_repeat('--',substr_count($v['path'],',')-$len)."<img src='/admin/images/company.png'>&nbsp;&nbsp;".$v['agent_name'];
        }
        if($agentId){
            //已登录, 查询位置表
            $data = DB::table('sa_room as r')
                -> LeftJoin('sa_area as a','a.a_id','=','r.r_a_id')
                -> LeftJoin('sa_building as b','b.b_id','=','r.r_b_id')
                -> select('r.r_id','r.r_name','a.a_name','b.b_name','r.r_floor')
                -> where(['r.r_agent_id'=>$get['ag']])
                -> where('r.r_name','like','%'.$get['room'].'%')
                -> where('a.a_name','like','%'.$get['area'].'%')
                -> where('b.b_name','like','%'.$get['building'].'%')
                -> paginate(1);
            $info = $data->all();
            foreach ($info as $k=>$v){
                //联查关系表和建筑表, 拿出mma_uid
                $temp = DB::table('sa_member_manager_area') -> select('mma_uid') -> where(['mma_r_id'=>$v['r_id']]) -> first();
                $info[$k]['mma_uid'] = $temp['mma_uid'];
            }
            foreach ($info as $k=>$v){
                $userStr = '';
                $idArr = explode(',',$v['mma_uid']);
                foreach ($idArr as $val){
                    //查询用户表
                    $userArr = DB::table('sa_member') -> select('username') -> where(['uid'=>$val]) -> first();
                    $userStr .= $userArr['username'].',';
                }
                $info[$k]['mma_username'] = substr($userStr,0,-1);
            }
        }else{
            $data = '';
            $info = '';
        }
        return view('admin.room.index',['agent'=>$agent,'data'=>$data,'info'=>$info,'request'=>$request->all(),'get'=>$get]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    //添加位置页面方法
    public function getCreate(Request $request)
    {
        //获取登录id
        // $agentId = session('agentId');
        $agentId = $request->cookie('agentId');
        //查询区域表
        $area = DB::table('sa_area') -> select('a_id','a_name') -> where(['a_agent_id'=>$agentId]) -> get();
        return view('admin.room.create',['area'=>$area]);
    }
    //添加位置页面方法
    public function getBecreate(Request $request)
    {
        //获取登录id
        // $agentId = session('agentId');
        $agentId = $request->cookie('agentId');
        //查询区域表
        $area = DB::table('sa_area') -> select('a_id','a_name') -> where(['a_agent_id'=>$agentId]) -> get();
        return view('admin.room.becreate',['area'=>$area]);
    }

    //添加位置处理方法
    public function postCreate(Request $request){
        //判断用户是否登录
        // $agentId = session('agentId');
        $agentId = $request->cookie('agentId');
        if($agentId) {
            //用户已登录
            //获取ajax数据
            $data = [];
            $data['r_a_id'] = $request -> input('area');
            $data['r_b_id'] = $request -> input('building');
            $data['r_name'] = $request -> input('room');
            $data['r_floor'] = $request -> input('floor');
            $data['r_agent_id'] = $agentId;
            if($request ->input('manage')){
                $manage = array_unique($request ->input('manage'));
            }else{
                $manage = [];
            }
            //插入位置表
            $r_id = DB::table('sa_room') -> insertGetId($data);
            if($r_id) {
                //位置表插入成功
                foreach ($manage as $k => $v) {
                    //查询用户表
                    $row = DB::table('sa_member')->where(['username' => $v])->first();
                    $manage[$k] = $row['uid'];
                }
                $mma_uid = implode(',', $manage);
                $mma_data = array(
                    'mma_uid' => $mma_uid,
                    'mma_a_id' => $data['r_a_id'],
                    'mma_b_id' => $data['r_b_id'],
                    'mma_r_id' => $r_id
                );
                $mma_id = DB::table('sa_member_manager_area')->insertGetId($mma_data);
                if ($mma_id) {
                    //关系表插入成功
                    $msg['status'] = '1';
                    $msg['msg'] = '操作成功';
                } else {
                    //关系表插入失败
                    $msg['status'] = '-2';
                    $msg['msg'] = '关系表插入失败';
                }
            }
        }else{
            //用户未登录
            $msg['status'] = '-3';
            $msg['msg'] = '请登录后添加';
        }
        echo json_encode($msg);
    }

    //编辑页面方法
    public function getEdit(Request $request){
        $r_id = $request -> input('r_id');
        //获取登录id
        // $agentId = session('agentId');
        $agentId = $request->cookie('agentId');
        //查询区域表
        $area = DB::table('sa_area') -> select('a_id','a_name') -> where(['a_agent_id'=>$agentId]) -> get();
        /*dd($area);*/
        //联查区域表和关系表
        $data = DB::table('sa_room as r')
            -> LeftJoin('sa_area as a','a.a_id','=','r.r_a_id')
            -> LeftJoin('sa_building as b','b.b_id','=','r.r_b_id')
            -> where(['r.r_id'=>$r_id])
            -> select('r.r_id','r.r_name','a.a_name','a.a_id','b.b_name','b.b_id','r.r_floor')
            -> first();
        //联查关系表和建筑表, 拿出mma_uid
        $temp = DB::table('sa_member_manager_area') -> select('mma_uid') -> where(['mma_r_id'=>$r_id]) -> first();
        if($temp){
            $data['mma_uid'] = $temp['mma_uid'];
        }else{
            $data['mma_uid'] = '';
        }
        //根据区域id查询建筑表
        $building = DB::table('sa_building') -> select('b_id','b_name') -> where(['b_a_id'=>$data['a_id']]) -> get();
        $userArr = [];
        $idArr = explode(',',$data['mma_uid']);
        foreach ($idArr as $val){
            //查询用户表
            $user = DB::table('sa_member') -> select('username') -> where(['uid'=>$val]) -> first();
            if($user['username'] != null){
                $userArr[] = $user['username'];
            }
        }
        $data['mma_username'] = $userArr;
        return view('admin.room.edit',['area'=>$area,'building'=>$building,'data'=>$data]);
    }

    //编辑位置信息处理方法
    public function postEdit(Request $request){
        //获取数据
        $r_id = $request ->input('r_id');
        //获取ajax数据
        $data = [];
        $data['r_a_id'] = $request -> input('area');
        $data['r_b_id'] = $request -> input('building');
        $data['r_name'] = $request -> input('room');
        $data['r_floor'] = $request -> input('floor');
        if($request ->input('manage')){
            $manage = array_unique($request ->input('manage'));
        }else{
            $manage = [];
        }
        //dd($manage);
        //修改房间表
        $row1 = DB::table('sa_room') -> where(['r_id'=>$r_id]) -> update($data);
        if($row1){
            $arr['status1'] = '1';
            //修改绑定表
            $sd_data = array(
                'a_id'=>$data['r_a_id'],
                'b_id'=>$data['r_b_id']
            );
            DB::table('sa_smoke_detector') -> where('r_id','=',$r_id) ->update($sd_data);
            DB::table('sa_electric_detector') -> where('r_id','=',$r_id) ->update($sd_data);
            DB::table('sa_infrared_detector') -> where('r_id','=',$r_id) ->update($sd_data);
            DB::table('sa_gas_detector') -> where('r_id','=',$r_id) ->update($sd_data);
            DB::table('sa_call_help_detector') -> where('r_id','=',$r_id) ->update($sd_data);
        }else{
            $arr['status1'] = '-1';
            $arr['msg1'] = '区域表未操作';
        }
        //修改关系表
        foreach ($manage as $k=>$v){
            //查询用户表
            $row = DB::table('sa_member') -> where(['username'=>$v]) -> first();
            $manage[$k] = $row['uid'];
        }
        $mma_uid = implode(',',$manage);
        $mma_data = array(
            'mma_a_id'=>$data['r_a_id'],
            'mma_b_id'=>$data['r_b_id'],
            'mma_r_id'=>$r_id,
            'mma_uid'=>$mma_uid
        );
        //查询关系表
        $res = DB::table('sa_member_manager_area') -> where(['mma_r_id'=>$r_id]) -> first();
        if($res){
            $row2 = DB::table('sa_member_manager_area') -> where(['mma_r_id'=>$r_id]) -> update($mma_data);
        }else{
            $row2 = DB::table('sa_member_manager_area') -> where(['mma_r_id'=>$r_id]) -> insertGetId($mma_data);
        }
        if($row2){
            $arr['status2'] = '1';
        }else{
            $arr['status2'] = '-1';
            $arr['msg2'] = '关系表未操作';
        }
        echo json_encode($arr);
    }
    // 删除位置信息
    public function getDelete(Request $request)
    {
        $id = base64_decode($request -> get('id'));
        $count = 0;
        $count += DB::table('sa_smoke_detector') -> where('r_id','=',$id) -> count();
        $count += DB::table('sa_electric_detector') -> where('r_id','=',$id) -> count();
        $count += DB::table('sa_infrared_detector') -> where('r_id','=',$id) -> count();
        $count += DB::table('sa_gas_detector') -> where('r_id','=',$id) -> count();
        $count += DB::table('sa_call_help_detector') -> where('r_id','=',$id) -> count();
        if($count != 0){
            return back() -> withInput() -> with('error','该位置下有'.$count.'个设备，请移除后再进行删除!');
        }else{
            DB::table('sa_room') -> where('r_id','=',$id) -> delete();
            DB::table('sa_member_manager_area') -> where('mma_r_id','=',$id) -> delete();
            return redirect('/admin/room/index') -> with('success','删除成功');
        }
    }

    //区域建筑联动方法
    public function postGetbuild(Request $request){
        $areaId = $request -> input('areaId');
        //查询建筑表
        $build = DB::table('sa_building') -> select('b_id','b_name') -> where(['b_a_id'=>$areaId]) -> get();
        echo json_encode($build);
    }

    //建筑位置联动方法
    public function postGetroom(Request $request){
        $buildingId = $request -> input('buildingId');
        //查询建筑表
        $room = DB::table('sa_room') -> select('r_id','r_name') -> where(['r_b_id'=>$buildingId]) -> get();
        echo json_encode($room);
    }
}
